package com.itheima.filter;

import com.itheima.utial.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@WebFilter("/*")
public class TokenFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        //获取请求路径
        String url = request.getRequestURL().toString();
        //如果是/login就放行
        if (url.contains("/login")){
            filterChain.doFilter(request,response);
            log.info("登录放行");
            return;
        }
        //获取请求头的token信息
            String token  = request.getHeader("token");
            if(token==null){
                response.setStatus(401);
                log.info("token为空");
                return;
            }
        try {
            JwtUtils.parseJWT(token);
            filterChain.doFilter(request,response);
            log.info("验证通过放行");
        } catch (Exception e) {
            log.info("token验证失败");
            response.setStatus(401);
        }
    }
}
